package it.sevenbits.view;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;


public class Journal {

    ResourceBundle bundle = null;
    ResourceBundle bundleLog = null;
    private static final Logger log4= Logger.getLogger(Journal.class);
    private String nameJournal;
    private String nameSlave;
    private String nameUndo;
    
    /**
     * Constructor
     */
    public Journal() {
        
        bundle = ResourceBundle.getBundle("journal");
        bundleLog = ResourceBundle.getBundle("logging");
        nameJournal = bundle.getString("journal.name");
        nameUndo = bundle.getString("journal.undo");
        nameSlave = bundle.getString("journal.slave");
        //PropertyConfigurator.configure(nameLog4j);
        log4.debug("Journal");
    }
    
    private void addTo(String command, String nameJourn) {
        try {
            //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
              //  new FileOutputStream(bundle.getString("journal."+nameJournal), true)));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(nameJourn, true)));
            
            writer.write(command);
            writer.newLine();
            writer.close();
        }
        catch(Exception e) {
            log4.warn("error in add to journal: " + e);
        }
    }
    
    /**
     * Adds to journal commands, which requested by the user
     * @param command
     */
    public void addToJournal(String command) {
        
        try {
            addTo(command, nameJournal);
        }
        catch(Exception e) {
            log4.warn("error in add to journal of commands: " + e);
        }
    }
    
    /**
     * Adds to undolog inverted commands
     * @param command
     */
    public void addToUndo(String command) {
        
        try {
            addTo(command, nameUndo);
        }
        catch(Exception e) {
            log4.warn("error in add to undolog: " + e);
        }
    }
    
    /**
     * Do copy of journal in slave journal
     */
    public void Replication() {
        
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream(nameJournal)));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(nameSlave, false)));
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }
            reader.close();
            writer.close();
        }
        catch(Exception e) {
            log4.warn("error in replication: " + e);
        }
    }
}
